package com.ccl.iot.dialogs;


import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.ccl.iot.R;
import com.ccl.iot.publics.Messager;
import com.ccl.iot.publics.ThreadPoolUtils;
import com.ccl.iot.publics.UIUtils;
import com.ccl.iot.template.ImageButtonView;
import com.ccl.iot.updater.HttpHelper;
import com.ccl.iot.views.SelectBrandView;
import com.ccl.iot.views.TestIrView;
import com.hzy.tvmao.KookongSDK;
import com.hzy.tvmao.interf.IRequestResult;
import com.hzy.tvmao.ir.Device;
import com.kookong.app.data.RemoteList;
import com.kookong.app.data.SpList;
import com.kookong.app.data.StbList;

import java.util.List;

public class SelectOperatorDialog extends Dialog {

    private ImageButtonView mIvBack;
    private EditText mEtSearch;
    private ListView mLvIptvs;
    private TextView mTvArea;
    private TextView mTvSelectArea;
    private AddSubBLirDialog.OnApplianceSelectListener mApplianceSelectListener;
    private String mDevName;
    private List<SpList.Sp> mSps;
    private IptvAdapter mAdapter;
    private int mAreaId;

    public SelectOperatorDialog(@NonNull Context context) {
        super(context, R.style.device_dialog_style_notitle);
        initView();
        initData();
        initListener();
    }

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_back:
                    cancel();
                    break;
                case R.id.tv_select_area:

                    break;
            }
        }
    };

    private void initView() {
        setContentView(R.layout.view_select_iptv);
        mIvBack = (ImageButtonView) findViewById(R.id.btn_back);
        mEtSearch = (EditText) findViewById(R.id.et_search_iptv);
        mLvIptvs = (ListView) findViewById(R.id.lv_iptv);
        mTvArea = (TextView) findViewById(R.id.tv_area);
        mTvSelectArea = (TextView) findViewById(R.id.tv_select_area);
    }

    private void initData() {
        mAdapter = new IptvAdapter();
        mLvIptvs.setAdapter(mAdapter);
    }

    private void initListener() {
        mIvBack.setOnClickListener(mOnClickListener);
        mTvSelectArea.setOnClickListener(mOnClickListener);

        mLvIptvs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final ProgressDialog progressDialog = new ProgressDialog(getContext(), ProgressDialog.THEME_DEVICE_DEFAULT_LIGHT);
                progressDialog.show();
                SpList.Sp sp = mSps.get(position);
                if (sp != null) {
                    if (sp.type == 1) {
                        KookongSDK.getIPTV(sp.spId, new IRequestResult<StbList>() {

                            @Override
                            public void onSuccess(String msg, StbList result) {
                                List<StbList.Stb> stbs = result.stbList;
                                progressDialog.cancel();
                                final HDCustomDialog dialog = new HDCustomDialog(getContext(), R.style.device_dialog_style_notitle);
                                SelectBrandView brandView = new SelectBrandView(getContext());
                                brandView.setStbBrands(stbs, Device.STB, new ModifyIconDialog.OnSelectChangeListener() {
                                    @Override
                                    public void onSelectChange() {
                                        dialog.cancel();
                                    }
                                }, mDevName, mApplianceSelectListener);

                                dialog.setContentView(getContext().getResources().getString(R.string.control_select), brandView);
                                dialog.show();
                            }

                            @Override
                            public void onFail(Integer errorCode, String msg) {
                                progressDialog.cancel();
                                Log.e("getIPTV", "msg: " + msg + ", errorCode: " + errorCode);
                                Messager.Show("msg: " + msg + ", errorCode: " + errorCode);
                            }
                        });

                    } else if (sp.type == 0) {
                        //获取指定运营商, 指定AreaId下的遥控器id brandid传0
                        KookongSDK.getAllRemoteIds(Device.STB, 0, sp.spId, mAreaId, new IRequestResult<RemoteList>() {

                            @Override
                            public void onSuccess(String msg, RemoteList result) {
                                List<Integer> remoteids = result.rids;
                                progressDialog.cancel();
                                final HDCustomDialog dialog = new HDCustomDialog(getContext(), R.style.device_dialog_style_notitle);
                                TestIrView testIrView = new TestIrView(getContext());
                                testIrView.setData(Device.STB, remoteids, new ModifyIconDialog.OnSelectChangeListener() {
                                    @Override
                                    public void onSelectChange() {
                                        dialog.cancel();
                                    }
                                }, mDevName, mApplianceSelectListener);

                                dialog.setContentView(getContext().getResources().getString(R.string.control_select), testIrView);
                                dialog.show();
                            }

                            @Override
                            public void onFail(Integer errorCode, String msg) {
                                progressDialog.cancel();
                                Log.e("getAllRemoteIds", "msg: " + msg + ", errorCode: " + errorCode);
                                Messager.Show("msg: " + msg + ", errorCode: " + errorCode);
                            }
                        });
                    }
                }
                cancel();
            }
        });
    }

    public void setInitData(String devName, AddSubBLirDialog.OnApplianceSelectListener listener) {
        mDevName = devName;
        mApplianceSelectListener = listener;
        getOperators();
    }

    private void getOperators() {
        ThreadPoolUtils.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                String json = HttpHelper.GetHttpRequestString("http://api.map.baidu.com/location/ip?ak=36af67d47e90ab8fa907841bf50fd54f");
                JSONObject jb = JSONObject.parseObject(json);
                JSONObject content = jb.getJSONObject("content");
                JSONObject address_detail = content.getJSONObject("address_detail");

                final String province = address_detail.getString("province");
                final String city = address_detail.getString("city");

                KookongSDK.getAreaId(province, city, city, new IRequestResult<Integer>() {
                    @Override
                    public void onSuccess(String msg, Integer result) {
                        mAreaId = result;
                        mTvArea.setText(province + city);

                        //获取指定AreaId下的运营商列表
                        KookongSDK.getOperaters(mAreaId, new IRequestResult<SpList>() {

                            @Override
                            public void onSuccess(String msg, final SpList result) {
                                mSps = result.spList;
                                mAdapter.notifyDataSetChanged();
                            }

                            @Override
                            public void onFail(Integer errorCode, String msg) {
                                Messager.Show("msg: " + msg + ", errorCode: " + errorCode);
                                Log.e("getOperaters", "msg: " + msg + ", errorCode: " + errorCode);

                            }
                        });
                    }

                    @Override
                    public void onFail(Integer integer, String s) {
                        Messager.Show("msg: " + s + ", errorCode: " + integer);
                        Log.e("getOperaters", "msg: " + s + ", errorCode: " + integer);
                    }
                });
            }
        });
    }

    private class IptvAdapter extends BaseAdapter {
        private int mItemHeight;

        public IptvAdapter() {
            mItemHeight = UIUtils.dp2px(40);
        }

        @Override
        public int getCount() {
            if (mSps != null && mSps.size() > 0) {
                return mSps.size();
            }
            return 0;
        }

        @Override
        public Object getItem(int position) {
            return mSps.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                TextView tv = new TextView(getContext());
                tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mItemHeight));
                tv.setGravity(Gravity.CENTER_VERTICAL);
                tv.setTextColor(Color.BLACK);
                tv.setBackgroundResource(R.drawable.selector_back_btn);
                tv.setPadding(mItemHeight / 2, 0, 0, 0);
                convertView = tv;
            }
            ((TextView) convertView).setText(mSps.get(position).spName);
            return convertView;
        }
    }

}
